package com.geeklan.smart.ui.dialog;

import android.content.Context;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.bigkoo.pickerview.adapter.ArrayWheelAdapter;
import com.geeklan.smart.R;
import com.geeklan.smart.databinding.DialogContentFoodBinding;
import com.geeklan.smart.databinding.DialogContentFoodSnacksBinding;
import com.geeklan.smart.databinding.LayoutFoodNumberBinding;
import com.geeklan.smart.databinding.LayoutTextviewBinding;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class SnacksBottomSheetDialog extends BaseBottomSheetDialog<DialogContentFoodSnacksBinding> {

    private NavAdapter navAdapter;
    private ContentAdapter contentAdapter;
    private Map<String, List<String>> dataMap; // 模拟数据源
    private int typePosition;
    private int numberPosition;
    private List<String> hourList;
    private List<String> minList;
    private String h = "00", m = "00";

    public SnacksBottomSheetDialog(Context context) {
        super(context);
    }

    @Override
    protected DialogContentFoodSnacksBinding createContentViewBinding(LayoutInflater inflater) {
        return DialogContentFoodSnacksBinding.inflate(inflater);
    }

    @Override
    protected void setupDialog() {
        super.setupDialog();
        setCancelableOutside(true); // 点击背景关闭
        setDraggable(false);
        setNonFullScreen();

        setDialogTitle(mContext.getString(R.string.snack));
        // 设置确定按钮逻辑
        setConfirmButtonVisible(true);
        setConfirmButtonText(mContext.getString(R.string.next));
        setConfirmButtonClickListener(v -> {
            if (mBinding.clStep2.getVisibility() == View.GONE) {
                mBinding.clFirstStep.setVisibility(View.GONE);
                mBinding.clStep2.setVisibility(View.VISIBLE);
                setConfirmButtonText(mContext.getString(R.string.ok));
                showBack(true);
            } else {
                if ("00".equals(h)) {
                    h = hourList.get(mBinding.wvHour.getCurrentItem());
                }
                if ("00".equals(m)) {
                    m = minList.get(mBinding.wvMin.getCurrentItem());
                }
                String time = h + ":" + m;
                confirmButtonClickListener.onClick(typePosition, numberPosition, time);
            }
        });

        setBackOnClickListener(v -> {
            mBinding.clFirstStep.setVisibility(View.VISIBLE);
            mBinding.clStep2.setVisibility(View.GONE);
            setConfirmButtonText(mContext.getString(R.string.next));
            showBack(false);
        });

        initDateWheelView();
        initData();
        // 设置左侧导航栏
        navAdapter = new NavAdapter(new ArrayList<>(dataMap.keySet()));
        mBinding.recyclerViewNav.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerViewNav.setAdapter(navAdapter);

        // 设置右侧内容列表
        contentAdapter = new ContentAdapter();
        mBinding.recyclerViewContent.setLayoutManager(new LinearLayoutManager(getContext()));
        mBinding.recyclerViewContent.setAdapter(contentAdapter);

        // 默认加载第一个导航项的数据
        if (!dataMap.isEmpty()) {
            String firstKey = dataMap.keySet().iterator().next();
            contentAdapter.updateData(dataMap.get(firstKey));
        }
        navAdapter.setOnItemClickListener(position -> {
            String selectedCategory = navAdapter.getItem(position);
            contentAdapter.updateData(dataMap.get(selectedCategory));
            numberPosition = 0;
        });


        mBinding.wvHour.setUnit(mContext.getString(R.string.hour));
        mBinding.wvHour.setCyclic(true); // 禁止循环滚动
        mBinding.wvHour.setAdapter(new ArrayWheelAdapter<>(hourList));
        mBinding.wvHour.setOnItemSelectedListener(index -> {
            h = hourList.get(index);

            List<String> minuteList = new ArrayList<>();

            if (Integer.parseInt(h) == currentHour) {
                // 只能选当前分钟之后
                for (int i = currentMinute; i < 60; i++) {
                    minuteList.add(String.format("%02d", i));
                }
            } else {
                // 可选所有分钟
                for (int i = 0; i < 60; i++) {
                    minuteList.add(String.format("%02d", i));
                }
            }
            minList = minuteList;
            m = minList.get(0);
            mBinding.wvMin.setAdapter(new ArrayWheelAdapter<>(minuteList));
            mBinding.wvMin.setCurrentItem(0);
        });


        mBinding.wvMin.setUnit(mContext.getString(R.string.min));
        mBinding.wvMin.setCyclic(true);
        mBinding.wvMin.setAdapter(new ArrayWheelAdapter<>(minList));
        mBinding.wvMin.setOnItemSelectedListener(index -> {
            m = minList.get(index);
        });
        mBinding.wvHour.setCurrentItem(0);
        mBinding.wvMin.setCurrentItem(0);
    }

    int currentHour;
    int currentMinute;

    private void initDateWheelView() {
        hourList = new ArrayList<>();
        minList = new ArrayList<>();
        Calendar now = Calendar.getInstance();
        currentHour = now.get(Calendar.HOUR_OF_DAY);
        currentMinute = now.get(Calendar.MINUTE);

        for (int hour = currentHour; hour <= 23; hour++) {
            hourList.add(String.valueOf(hour < 10 ? ("0" + hour) : hour));
        }

        for (int min = currentMinute; min <= 59; min++) {
            minList.add(String.valueOf(min < 10 ? ("0" + min) : min));
        }

        h = hourList.get(0);
        m = minList.get(0);
    }

    private ConfirmButtonClickListener confirmButtonClickListener;

    public void setConfirmButtonClickListener(ConfirmButtonClickListener confirmButtonClickListener) {
        this.confirmButtonClickListener = confirmButtonClickListener;
    }

    public interface ConfirmButtonClickListener {
        void onClick(int typePosition, int numberPosition, String time);
    }

    private void initData() {
        dataMap = new HashMap<>();
        dataMap.put("猫条", setItems1());
        dataMap.put("干粮", setItems2());
    }

    private List<String> setItems1() {
        List<String> items = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            items.add("条");
        }
        return items;
    }

    private List<String> setItems2() {
        List<String> items = new ArrayList<>();
        for (int i = 1; i <= 7; i++) {
            items.add("份（约" + i * 20 + "g）");
        }
        return items;
    }

    // 左侧导航栏适配器
    class NavAdapter extends RecyclerView.Adapter<NavAdapter.MyViewHolder> {
        private OnItemClickListener onItemClickListener;
        private final List<String> navItems;


        public NavAdapter(List<String> navItems) {
            this.navItems = navItems;
        }

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutTextviewBinding layoutTextviewBinding = LayoutTextviewBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new MyViewHolder(layoutTextviewBinding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.textView.setText(navItems.get(position));
            holder.textView.setTextColor(typePosition == position ? 0xFF7EBF7E : 0xFF999999);
            holder.textView.setBackgroundColor(typePosition == position ? 0x449CCC9C : 0xFFFFFFFF);
            holder.textView.setOnClickListener(v -> {
                typePosition = holder.getAdapterPosition();
                navAdapter.notifyDataSetChanged();
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(typePosition);
                }
            });
        }

        @Override
        public int getItemCount() {
            return navItems.size();
        }

        public String getItem(int position) {
            return navItems.get(position);
        }


        interface OnItemClickListener {
            void onItemClick(int position);
        }

        static class MyViewHolder extends RecyclerView.ViewHolder {
            TextView textView;
            TextView tvUnit;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                textView = (TextView) itemView;
            }
        }

        public void setOnItemClickListener(OnItemClickListener listener) {
            this.onItemClickListener = listener;
        }
    }

    // 右侧内容适配器
    class ContentAdapter extends RecyclerView.Adapter<ContentAdapter.MyViewHolder> {
        private OnItemClickListener onItemClickListener;
        private final List<String> contentItems = new ArrayList<>();

        @NonNull
        @Override
        public MyViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            LayoutFoodNumberBinding layoutFoodNumberBinding = LayoutFoodNumberBinding.inflate(LayoutInflater.from(parent.getContext()), parent, false);
            return new MyViewHolder(layoutFoodNumberBinding.getRoot());
        }

        @Override
        public void onBindViewHolder(@NonNull MyViewHolder holder, int position) {
            holder.tvNumber.setText(String.valueOf(position + 1));
            holder.tvNumber.setTextColor(numberPosition == position ? 0xFF7EBF7E : 0xFF999999);
            holder.tvUnit.setText(contentItems.get(position));
            holder.tvUnit.setTextColor(numberPosition == position ? 0xFF7EBF7E : 0xFF999999);
            holder.linearLayout.setBackgroundColor(numberPosition == position ? 0x449CCC9C : 0xFFFFFFFF);
            holder.linearLayout.setOnClickListener(v -> {
                numberPosition = holder.getAdapterPosition();
                notifyDataSetChanged();
                if (onItemClickListener != null) {
                    onItemClickListener.onItemClick(typePosition);
                }
            });
        }

        @Override
        public int getItemCount() {
            return contentItems.size();
        }

        public void updateData(List<String> newItems) {
            contentItems.clear();
            contentItems.addAll(newItems);
            notifyDataSetChanged();
        }


        static class MyViewHolder extends RecyclerView.ViewHolder {
            TextView tvNumber;
            TextView tvUnit;
            LinearLayout linearLayout;

            public MyViewHolder(@NonNull View itemView) {
                super(itemView);
                linearLayout = (LinearLayout) itemView;
                tvUnit = (TextView) itemView.findViewById(R.id.tvUnit);
                tvNumber = (TextView) itemView.findViewById(R.id.tvNumber);
            }
        }

        public void setOnItemClickListener(OnItemClickListener listener) {
            this.onItemClickListener = listener;
        }

        interface OnItemClickListener {
            void onItemClick(int position);
        }
    }

}
